﻿#include "CodeOperator.h"
#include <QDir>

CodeOperator::CodeOperator(const QString &codeParDir, QObject *parent)
	: QObject(parent)
	, m_codeParDir(codeParDir)
	, m_codePublishDir("CTPProject")
{
	if (!m_codeParDir.endsWith('/'))
	{
		m_codeParDir += '/';
	}
}

CodeOperator::~CodeOperator()
{
}

void CodeOperator::PublishCode()
{
	QString codeDir = m_codeParDir + m_codePublishDir;
	//QDir dir;
	//QStringList copyList;
	//copyList << "MarketQuotations" << "Trade";
	//foreach(const QString &pDir, copyList)
	//{
	//	dir.mkpath(m_codeParDir + m_codePublishDir + '/' + pDir);
	//}
	// 复制CTP_SE
	copyDir(m_codeParDir + "CTPSimNow6.6.1", m_codeParDir + m_codePublishDir + "/CTP_SE");
	// 复制MarketQuotations
	copyCode(m_codeParDir + "MarketQuotations", m_codeParDir + m_codePublishDir + "/MarketQuotations");
	// 复制Trade
	copyCode(m_codeParDir + "Trade", m_codeParDir + m_codePublishDir + "/Trade");
	copyDir(m_codeParDir + "Trade/lib_json", m_codeParDir + m_codePublishDir + "/Trade/lib_json");

	copyCode(m_codeParDir + "SymbolObtainer", m_codeParDir + m_codePublishDir + "/SymbolObtainer");
	copyCode(m_codeParDir + "TimeSegment", m_codeParDir + m_codePublishDir + "/TimeSegment");
	// 复制Public
	copyDir(m_codeParDir + "Public", m_codeParDir + m_codePublishDir + "/Public");

	QFile::copy(m_codeParDir + "/CMakeLists.txt", m_codeParDir + m_codePublishDir + "/CMakeLists.txt");
	QFile::copy(m_codeParDir + "/setting.opt", m_codeParDir + m_codePublishDir + "/setting.opt");
}

void CodeOperator::ClearPublishCode()
{
	QString path = m_codeParDir + m_codePublishDir;
	QDir dir(path);
	dir.removeRecursively();
}

void CodeOperator::copyDir(const QString & src, const QString & dst)
{
	QDir srcDir(src);
	QDir dstDir(dst);

	if (!dstDir.exists()) {
		dstDir.mkpath(dst);
	}

	QFileInfoList list = srcDir.entryInfoList();

	foreach(QFileInfo info, list) 
	{
		QString pFile = info.fileName();
		if (pFile == "." || pFile == "..")
		{
			continue;
		}
		if (info.isDir()) 
		{
			// 创建文件夹，递归调用该函数
			copyDir(info.filePath(), dst + "/" + pFile);
			continue;
		}
		// 文件拷贝
		QFile file(info.filePath());
		file.copy(dst + "/" + pFile);
	}
}

void CodeOperator::copyCode(const QString &pDir, const QString &pdstDir)
{
	QDir srcDir(pDir);
	QFileInfoList list = srcDir.entryInfoList();
	
	QDir dstDir(pdstDir);
	if (!dstDir.exists()) {
		dstDir.mkdir(pdstDir);
	}

	foreach(QFileInfo info, list) {
		QString pFile = info.fileName();
		if (pFile == "." || pFile == "..") {
			continue;
		}
		if (info.isDir()) 
		{
			continue;
		}
		
		if (pFile.endsWith(".h") || pFile.endsWith(".cpp") || pFile.startsWith("CMakeLists"))
		{
			QFile file(info.filePath());
			file.copy(pdstDir + '/' + pFile);
		}
	}
}
